﻿using DreamCMS.BLL.Factory.Interface;
using DreamCMS.Entity;
using DreamCMS.WebCore.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamCMS.DAL.DataAccessObject
{
    public class StatisticDAO:IStatisticDAO
    {
        /// <summary>
        /// 更新统计信息
        /// </summary>
        /// <param name="statistic">统计实体</param>
        /// <returns>是否更新成功</returns>
        public bool UpdateStatistic(StatisticInfo statistic)
        {
            string sql = "update [dm_SiteSetting] set postcount=@PostCount,commentcount=@CommentCount,visitcount=@VisitCount,tagcount=@TagCount";
            OleDbParameter[] paras = {
                                         AccessHelper.MakeParam(
"@PostCount",OleDbType.Integer,4,ParameterDirection.Input,statistic.PostCounts),
AccessHelper.MakeParam("@CommentCount",OleDbType.Integer,8,ParameterDirection.Input,statistic.CommentCounts),
AccessHelper.MakeParam("@VisitCount",OleDbType.Integer,8,ParameterDirection.Input,statistic.VisitCounts),
AccessHelper.MakeParam("@TagCount",OleDbType.Integer,8,ParameterDirection.Input,statistic.TagCounts)
                                     };
            long rel=AccessHelper.ExecuteNonQuery(CommandType.Text, sql, paras);
            if(rel==1)
            {
                return true;
            }
            return false;
        }


        /// <summary>
        /// 获取统计信息
        /// </summary>
        /// <returns>统计信息实体</returns>
        public StatisticInfo GetStatistic()
        {
            string sql = "select top 1 [siteid],[postcount],[commentcount],[visitcount],[tagcount] from [dm_SiteSetting]";
            DataSet ds=AccessHelper.ExecuteDataSet(CommandType.Text, sql);
            if(ds.Tables.Count<1 || ds.Tables[0].Rows.Count<1)
            {
                string insertText = "insert into [dm_SiteSetting] ([postcount],[commentcount],[visitcount],[tagcount],[settingxml]) values ( '0','0','0','0','<?xml version=\"1.0\" encoding=\"utf-8\"?><SiteSettingInfo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></SiteSettingInfo>')";
                AccessHelper.ExecuteNonQuery(CommandType.Text, insertText);
            
                StatisticInfo newstatic = new StatisticInfo();
                return newstatic;
            }
            StatisticInfo statistic = new StatisticInfo();
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.Rows[0];
            statistic.PostCounts = Convert.ToInt64(dr["postcount"]);
            statistic.VisitCounts = Convert.ToInt64(dr["visitcount"]);
            statistic.CommentCounts = Convert.ToInt64(dr["commentcount"]);
            statistic.TagCounts = Convert.ToInt64(dr["tagcount"]);
            return statistic;
        }
    }
}
